import datetime
import json
import time
from django.http import JsonResponse
from django.utils import timezone
from django.views import View
from django_redis import get_redis_connection
from house.models import House, HouseImage
from order.models import Order
from order.tests import compare_time


class AddOrderView(View):
    ''' 添加和获取订单'''

    def post(self, request):
        '''添加订单'''
        user = request.user

        if user is None and not user.is_authenticated:
            return JsonResponse({
                'errno': 4101,
                'errmsg': '请先登录'
            })
        json_dict = json.loads(request.body.decode())

        house_id = json_dict.get('house_id')
        start_date = json_dict.get('start_date')
        end_date = json_dict.get('end_date')

        if not all([house_id, start_date, end_date]):
            return JsonResponse({
                'errno': 400,
                'errmsg': '缺少必传参数'
            })
        # 判断是不是自己下自己的单
        try:
            house = House.objects.get(id=house_id)
            # order = Order.objects.get(house=house_id)
        except Exception as e:
            return JsonResponse({
                'errno': 400,
                'errmsg': '连接数据库报错'
            })
        if house.user == user.id:
            return JsonResponse({
                'errno': 400,
                'errmsg': '自己不能下自己的单'
            })
        # order_id = timezone.localtime().strftime('%Y%m%d%H%M%S')
        # 保存订单基本信息

        s_time = time.strptime(start_date, '%Y-%m-%d')
        e_time = time.strptime(end_date, '%Y-%m-%d')
        st = datetime.datetime(s_time.tm_year, s_time.tm_mon, s_time.tm_mday)
        en = datetime.datetime(e_time.tm_year, e_time.tm_mon, e_time.tm_mday)
        days = en - st
        day = (en - st).days

        # print(type(datetime.date(*map(int, start_date.split('-')))))
        # start_date = datetime.date(*map(int, start_date.split('-')))
        # end_date = datetime.date(*map(int, end_date.split('-')))

        try:
            order_list = Order.objects.filter(house=house_id)

            for order in order_list:
                start_date1 = order.begin_date
                end_date1 = order.end_date
                # 判断房子在日期内有没有被人预定
                start_date1 = str(start_date1)
                end_date1 = str(end_date1)
                result = compare_time(start_date1, end_date1, start_date, end_date)
                if result == 'NG':
                    return JsonResponse({
                        'errno': 400,
                        'errmsg': '房子已经被订了'
                    })
        except Exception as e:
            return JsonResponse({
                'errno': 400,
                'errmsg': '无法确定房子是否被确定'
            })

        Order.objects.create(
            user=user,
            house_id=house_id,
            begin_date=start_date,
            end_date=end_date,
            days=day,
            house_price=house.price,
            amount=int(house.price) * int(day),
            status=1,
            # status = Order.ORDER_STATUS_CHOICES['WAIT_ACCEPT']
        )

        return JsonResponse({
            "data": {
                "order_id": 1
            },
            "errno": "0",
            "errmsg": "下单成功"
        })

    def get(self, request):
        '''获取订单列表'''

        user = request.user
        if user is None and not user.is_authenticated:
            return JsonResponse({
                'errno': 4101,
                'errmsg': '请先登录'
            })
        role = request.GET.get('role')

        orders = []

        if role == 'custom':
            # 查询我的订单

            order_list = Order.objects.filter(user=user.id)
            try:
                for order in order_list:
                    houses = House.objects.filter(id=order.house_id)
                    for house in houses:
                        image = HouseImage.objects.filter(house_id=house.id)
                        img_url = image[0].url
                        order_status_list = {0: 'WAIT_ACCEPT', 1: 'WAIT_ACCEPT', 2: 'WAIT_ACCEPT', 3: 'WAIT_COMMENT',
                                             4: 'COMPLETE', 5: 'CANCELED', 6: 'REJECTED'}
                        # order_status = order_status_list[order.status]
                        # print(order_status)

                        create_time = order.create_time
                        time_change = create_time.strftime('%Y-%m-%d %H:%M')

                        orders.insert(0, {
                            "amount": order.amount,
                            "comment": order.comment,
                            "ctime": time_change,
                            "days": order.days,
                            "end_date": order.end_date,
                            "img_url": img_url,
                            "order_id": order.id,
                            "start_date": order.begin_date,
                            "status": order_status_list[order.status],
                            "title": house.title
                        })
            except Exception as e:
                return JsonResponse({
                    'errno': 400,
                    'errmsg': '数据库查询失败'
                })
            return JsonResponse({
                'data': {
                    'orders': orders
                },
                'errmsg': 'ok',
                'errno': 0,

            })
        else:
            '查询客户的订单'
            house_list = House.objects.filter(user=user.id)
            try:
                for house in house_list:
                    order_ll = Order.objects.filter(house_id=house.id)
                    for order in order_ll:
                        image = HouseImage.objects.filter(house_id=house.id)
                        img_url = image[0].url
                        create_time = order.create_time
                        time_change = create_time.strftime('%Y-%m-%d %H:%M')
                        order_status_list = {0: 'WAIT_ACCEPT', 1: 'WAIT_ACCEPT', 2: 'WAIT_ACCEPT', 3: 'WAIT_COMMENT',
                                             4: 'COMPLETE', 5: 'CANCELED', 6: 'REJECTED'}

                        orders.insert(0, {
                            "amount": order.amount,
                            "comment": order.comment,
                            "ctime": time_change,
                            "days": order.days,
                            "end_date": order.end_date,
                            "img_url": img_url,
                            "order_id": order.id,
                            "start_date": order.begin_date,
                            "status": order_status_list[order.status],
                            "title": house.title
                        })
            except Exception as e:
                return JsonResponse({
                    'errno': 400,
                    'errmsg': '数据库查询失败'
                })
            return JsonResponse({
                'data': {
                    'orders': orders
                },
                'errmsg': 'ok',
                'errno': 0,

            })


class StatusOrderView(View):
    '''接单和拒单'''

    def put(self, request):
        json_dict = json.loads(request.body.decode())
        path1 = request.path
        order_id = path1.replace('/api/v1.0/orders/', '').replace('/status', '')

        action = json_dict.get('action')
        reason = json_dict.get('reason')
        user = request.user

        if action == 'accept':
            pending_order = Order.objects.get(id=order_id)
            pending_order.status = 3
            pending_order.save()

            return JsonResponse({
                "errno": "0",
                "errmsg": "操作成功"
            })
        else:
            pending_order = Order.objects.get(id=order_id)
            pending_order.status = 6
            pending_order.comment = reason
            pending_order.save()
            return JsonResponse({
                "errno": "0",
                "errmsg": "操作成功"
            })


class CommentView(View):
    '''评价订单'''

    def put(self, request):
        json_dict = json.loads(request.body.decode())
        path1 = request.path
        order_id = path1.replace('/api/v1.0/orders/', '').replace('/comment', '')

        comment = json_dict.get('comment')
        pending_order = Order.objects.get(id=order_id)
        pending_order.status = 4
        pending_order.comment = comment
        pending_order.save()
        return JsonResponse({
            "errno": "0",
            "errmsg": "评论成功"
        })
